package com.hydra.auth.utils;

import cn.hutool.core.bean.BeanUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hydra.auth.entity.SysUser;
import com.hydra.base.utils.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Map;

/**
 * 权限工具
 * 用于获取当前登录的用户信息等等
 * @Author Hydra
 * @Date 2022/5/9 10:04
 */
@Slf4j
public class SecurityUtil {

    public static Authentication getAuthentication(){
        return SecurityContextHolder.getContext().getAuthentication();
    }

    public static SysUser getPrincipal(){
        Authentication authentication = getAuthentication();
        return getPrincipal(authentication);
    }
    public static SysUser getPrincipal(Authentication authentication){
        if(authentication != null){
            Object principal = authentication.getPrincipal();
            if(principal instanceof SysUser){
                return (SysUser)principal;
            }else if(principal instanceof Map){
                String json = JsonUtil.toJsonString(principal);
                return JsonUtil.parseObject(json, SysUser.class);
            }else if(principal instanceof UsernamePasswordAuthenticationToken){
                Object obj = ((UsernamePasswordAuthenticationToken) principal).getPrincipal();
                String json = JsonUtil.toJsonString(obj);
                return JsonUtil.parseObject(json, SysUser.class);
            }
        }
        return null;
    }

}
